import User from '../../../Models/user';
import Money from "../../../Models/money";
import Statics from "../../../Models/statics";
import Post from "../../../Models/post";
import Point from '../../../Models/point';
import moment from 'moment';

const schedule = require('node-schedule');
const userEntity = new User();
const moneyEntity = new Money();
const staticsEntity = new Statics();
const postEntity = new Post();
const pointEntity = new Point();

function scheduleCronstyle() {
  // '30 1 1 * * *'
  // '30 * * * * *'
  schedule.scheduleJob('30 1 1 * * *', function () {

    const yesterday = moment().add(-1, 'days')
    const yesterdayStr = yesterday.format('YYYY-MM-DD');
    const theDayBeforeterday = moment().add(-2, 'days');
    const theDayBeforeterdayStr = theDayBeforeterday.format('YYYY-MM-DD');
    const yStart = moment({ hour: 0, minute: 0, second: 0 }).add(-1, 'days').unix();
    const yEnd = moment({ hour: 23, minute: 59, second: 59 }).add(-1, 'days').unix();
    // 当前零点多的时候统计昨天的
    userEntity.getAllUsers({ createTime: { $gt: yStart, $lt: yEnd } }, (err, users) => {
        if (err) {
            return;
        }
        const yNumber = users.length;
        staticsEntity.getStatics({
          dateString: theDayBeforeterdayStr
        }, (err, tdbs) => {
            if (err) {
                return;
            }
            const s = {
              dateString: yesterdayStr,
              type: 0,
              dailyValue: yNumber,
              sum: yNumber
            }
            if (!tdbs) {
              s.sum = yNumber
            } else {
              const { sum } = tdbs;
              s.sum = sum + yNumber
            } 
            staticsEntity.saveStatics(s);     
        });     
    });

    moneyEntity.getAllMoneys({ createTime: { $gt: yStart, $lt: yEnd }, toUserId: 'system' }, (err, momeys) => {
      if (err) {
          return;
      }
      const yNumber = momeys.reduce((t,c)=>{
        t+=c.money;
        return t;
      }, 0);
      staticsEntity.getStatics({
        dateString: theDayBeforeterdayStr
      }, (err, tdbs) => {
          if (err) {
              return;
          }
          const s = {
            dateString: yesterdayStr,
            type: 1,
            dailyValue: yNumber,
            sum: yNumber
          }
          if (!tdbs) {
            s.sum = yNumber
          } else {
            const { sum } = tdbs;
            s.sum = sum + yNumber
          } 
          staticsEntity.saveStatics(s);     
      });     
    });

    moneyEntity.getAllMoneys({ createTime: { $gt: yStart, $lt: yEnd }, fromUserId: 'system' }, (err, momeys) => {
      if (err) {
          return;
      }
      const yNumber = momeys.reduce((t,c)=>{
        t+=c.money;
        return t;
      }, 0);
      staticsEntity.getStatics({
        dateString: theDayBeforeterdayStr
      }, (err, tdbs) => {
          if (err) {
              return;
          }
          const s = {
            dateString: yesterdayStr,
            type: 2,
            dailyValue: yNumber,
            sum: yNumber
          }
          if (!tdbs) {
            s.sum = yNumber
          } else {
            const { sum } = tdbs;
            s.sum = sum + yNumber
          } 
          staticsEntity.saveStatics(s);     
      });     
    });


    const start = moment({ hour: 0, minute: 0, second: 0 }).add(-1, 'days').unix();
    const end = moment({ hour: 23, minute: 59, second: 59 }).add(-1, 'days').unix();
    const query = { createTime: { $gt: start, $lt: end } }
    postEntity.getBest10Posts(query, (err, posts) => {
        if (err || !posts) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const userObj = posts.reduce((t,c, index)=>{
          const num = 100-index*10;
          if (t[c.creatorId]) {
            t[c.creatorId] += num
          } else {
            t[c.creatorId] = num
          }
          return t;
        }, {});
        Object.keys(userObj).forEach(u=>{
          userEntity.getUser({ _id: u }, (err, user) => {
            const p = userObj[u];
            const point = (user.point || 0) + p;
            const leftPoint = (user.leftPoint || 0) + p;
            pointEntity.savePoint({creatorId: u, score: p, desc: `${start.format('YYYY-MM-DD')}热搜加分`},err=>{})
            userEntity.updateUser({ _id: u, point, leftPoint }, err=>{})
          })
        })
    })
  });
}

scheduleCronstyle();


export function getAllStaticss(req, res, next) {
  const {  ...query } = req.body;
  console.log(query, 111)
  staticsEntity.getAllStaticss(query, (err, stats) => {
    console.log(stats, 22)
      if (err) {
          return res.status(200).json({ code: 1, msg: '服务器开小差' });
      }
      return res.status(200).json({ code: 0, data: stats });
  })
}